package com.si.control.action;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Random;

import com.si.ui.enumn.EConstant;

public class RandomCollageAction extends CollageAction {
	
	private final Random random;
	
	public RandomCollageAction() {
		this.random = new Random();
	}

	@Override
	protected BufferedImage doCollage(final List<BufferedImage> argument) throws Exception {
		final BufferedImage result = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
		final int length = argument.size();
		BufferedImage image = argument.get(this.randomIndex(length));
		final int limit = EConstant.Randomness.getValue();
		int pcount = 0;
		int count = 0;
		int xi = 0;
		for(int x = 0; x < this.width; x++) {
			int yi = 0;
			for(int y = 0; y < this.height; y++) {
				if(xi >= image.getWidth()) xi = 0;
				if(yi >= image.getHeight()) yi = 0;
				final int rgb = image.getRGB(xi, yi);
				yi++;
				result.setRGB(x, y, rgb);
				count++;
				pcount++;
				if(count > limit) {
					image = argument.get(this.randomIndex(length));
					count = 0;
				}
			}
			xi++;
		}
		return result;
	}

	private int randomIndex(final int length) {
		return this.random.nextInt() & (length-1);
	}
}
